#!/usr/bin/perl

use warnings;
use strict;

#################################################################################
## This file inserts the inputs VDD and VSS to every
## module within a structural Verilog file. It also
## replaces every instance of "));" with "), .VDD(VDD), .VSS(VSS));"
## and replaces 1'b0 with VSS and 1'b1 with VDD.
##
## Updated August 20, 2010 By Alicia Klinefelter
##
## Add Verilog file as first argument and desired output file as the second:
## i.e, perl addVDDVSS.pl <structural filename>.v <desired output filename>.v
#################################################################################

my $infile = $ARGV[0];
my $outfile = $ARGV[1];


# Open files
open(IN, "$infile") || die("Could not open file!");
open(OUT, ">$outfile") || die("Could not open file!");

my $replace_str1 = ",\n    VDD,\n    VSS);\n\n   input VDD, VSS;";
my $replace_str2 = "), .VDD(VDD), .VSS(VSS));";
my $line;

#insert VDD and VSS as inputs to all modules
while ($line = <IN>) {
    chomp($line);
    $line =~ s/1'b0/VSS/g;
    $line =~ s/1'b1/VDD/g;
	if (substr($line, 0, 6) eq "module") {
		print OUT $line . "\n";
		$line = <IN>;
		$line =~ s/\)\);/$replace_str2/g;
		while ($line !~ m/\);/) {
			print OUT $line;
			$line = <IN>;
			$line =~ s/\)\);/$replace_str2/g;
		}
		$line = "    " . substr($line, 0, length($line)-3) . $replace_str1;
		$line =~ s/\)\);/$replace_str2/g;
		print OUT $line . "\n";
	}
	else {
		if ($line =~ m/\)\);/) {
			$line =~ s/\)\);/$replace_str2/g;
			print OUT $line . "\n";
		}
		else {
			print OUT $line . "\n";
		}
	}

}
 